package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import com.usian.common.fastDFS.FastDFSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1:上传文件
        String filePath="";
        try {
            filePath = fastDFSClientUtil.uploadFile(multipartFile);
            System.out.println("图片地址：=="+filePath);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //2:保存表数据
        WmUser wmUser = WmThreadLocalUtils.getUser();

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(filePath);  //图片地址
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());

        save(wmMaterial);

        //拼接图片路径  http://192.168.58.138/group1/M00.....aaa.jpg
        wmMaterial.setUrl(fileServerUrl+filePath);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        dto.checkParam();

        //2.带条件分页查询
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取当前登录的用户
        Integer uid = WmThreadLocalUtils.getUser().getId();
        lambdaQueryWrapper.eq(WmMaterial::getUserId,uid);
        if(dto.getIsCollection() != null && dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //  select * from wm_material where user_id=? and is_collection=1 order by creat_time  desc

        Page page = new Page(dto.getPage(), dto.getSize());
        IPage iPage = page(page, lambdaQueryWrapper);


        PageResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getPage(),(int)page.getTotal());
        List<WmMaterial> list = iPage.getRecords();


        list.stream().map(a->{a.setUrl(fileServerUrl+a.getUrl()); return a;}).collect(Collectors.toList());

        responseResult.setData(list);

        return responseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 删除前校验
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前图片被引用");
        }
        //1:删服务器图片
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        fastDFSClientUtil.delFile(wmMaterial.getUrl());

        //2:素材表
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {

        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer uid = WmThreadLocalUtils.getUser().getId();

        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, uid));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
